(ns org.mikrosopht.movie
  (:use [clojure.contrib.command-line :only (with-command-line)]
        [clojure.contrib.duck-streams :only (reader with-in-reader)]
        [clojure.contrib.json :only (read-json print-json)])
  (:import (java.net URLEncoder)))

(def google-search-prefix "http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=")

(defn- quote-string [string]
  (apply str [\" string \"]))

(defn google-search [criteria]
  (let [search-string (apply str (interpose " " criteria))]
    (let [search-url (apply str [google-search-prefix (URLEncoder/encode search-string "UTF-8")])]
      (with-in-reader (reader search-url)
        (with-open [rdr *in*]
          (if-let [result (first (((read-json rdr) :responseData) :results))]
            [(result :url)] []))))))
        
(defn find-metacritic-review-url [name]
  (first (filter #(re-matches #".*(/movie/|titles).*" %) (google-search [name "site:metacritic.com"]))))

(defn find-rotten-review-url [name]
  (first (filter #(.contains % "/m/") (google-search [name "site:rottentomatoes.com"]))))

(defn find-trailer [name]
  (first (google-search [name "site:youtube.com" "trailer"])))

(defn find-imdb [name]
  (first (google-search [name "site:imdb.com"])))

(with-command-line *command-line-args*
  "movie-search -- Find movie review URLs or trailers"
  [[imdb? "IMDB page"]
   [metacritic-review? "Metacritic Review"]
   [rotten-review? "Rotten Tomatoes Review"]
   [trailer? "YouTube trailer"]
   movie-names]
  (cond
    imdb? (dorun (map #(println (find-imdb %)) movie-names))
    metacritic-review? (dorun (map #(println (find-metacritic-review-url %)) movie-names))
    rotten-review? (dorun (map #(println (find-rotten-review-url %)) movie-names))
    trailer? (dorun (map #(println (find-trailer %)) movie-names))))
